//
//  TypeDao.swift
//  SimpleCal
//
//  Created by 杜晓祥 on 2021/11/2.
//

import Foundation
import CoreData
import Cocoa

class  TypeDao: NSObject {
    
    func save(name:String, remark:String) {
        let app = NSApplication.shared.delegate as! AppDelegate
        let context = app.persistentContainer.viewContext
        let type = NSEntityDescription.insertNewObject(forEntityName: "TypeEntity", into: context) as! TypeEntity
        type.id = CalendarUtil.milliStamp
        type.name = name
        type.remark = remark
        do {
            try context.save()
            print("保存成功")
        } catch {
            fatalError("不能保存\(error)")
        }
    }
    
    func query () {
        let app = NSApplication.shared.delegate as! AppDelegate
        let context = app.persistentContainer.viewContext
        
        let fetchRequest = NSFetchRequest<TypeEntity>(entityName: "TypeEntity")
        fetchRequest.fetchLimit = 10
        fetchRequest.fetchOffset = 0
        let predicate = NSPredicate(format: "name !=''", "")
        fetchRequest.predicate = predicate
        do {
            let fetchedObjects = try context.fetch(fetchRequest)
            for info in fetchedObjects {
                print("id=\(info.id)")
                
                print("name=\(String(describing: info.name))")
            }
        } catch {
            fatalError("查询失败:\(error)")
        }
    }
    
}
